package com.glodon.ggzy.jgpt.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.glodon.ggzy.core.model.Page;
import com.glodon.ggzy.core.utils.Constants;
import com.glodon.ggzy.core.utils.JsonUtils;
import com.glodon.ggzy.core.utils.PageSearchModel;
import com.glodon.ggzy.core.utils.Tools;
import com.glodon.ggzy.entity.GgJsProjectInfo;
import com.glodon.ggzy.entity.GgJsSchedule;
import com.glodon.ggzy.entity.JgUser;
import com.glodon.ggzy.fwpt.service.IJsgcProjectService;
import com.glodon.ggzy.jgpt.service.IJgptCqjyService;
import com.glodon.ggzy.jgpt.service.IJgptZfcgService;
import com.glodon.ggzy.sso.utils.TimeUtil;
import com.glodon.ggzy.user.service.IJgptUserService;
import com.glodon.ggzy.vo.AuthorityMenu;
import com.glodon.ggzy.vo.DataInfo;
import com.glodon.ggzy.vo.JgptCqjy;
import com.glodon.ggzy.vo.JgptJsgcDetail;
import com.glodon.ggzy.vo.JgptProject;
import com.glodon.ggzy.vo.JgptProjectInfoVO;
import com.glodon.ggzy.vo.ZfcgStaticsVO;

/**
 * 
 * 监管平台，统计分析controller
 * @author wues
 * @date 2013/06/25
 */
@Controller
public class JgptController {

	protected Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	IJsgcProjectService jsgcProjectService;

	@Autowired
	private IJgptCqjyService jgptCqjyService;

	@Autowired
	IJgptZfcgService jgptZfcgService;

	@Autowired
	IJgptUserService jgptUserService;

	@InitBinder
	public void initBinder(WebDataBinder binder) {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		dateFormat.setLenient(false);
		binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
	}

	/**
	 * 首页-监管平台
	 * @param model
	 * @return
	 */
	@RequestMapping("/jgpt/jgpt_index")
	public String getJgptIndex(Model model) {
		return "/jgpt/jgpt_index";
	}

	/**
	 * 建设工程 - 建设工程 分页 
	* @param model
	* @return
	*/
	@RequestMapping("/jgpt/jgpt_project_subway")
	public String zbggJsgcPageList(Model model, HttpServletRequest request, String menuId) {

		/*****************增加权限*********************/
		AuthorithFilterMenu(model, request, menuId);

		return "/jgpt/jgpt_project_subway";
	}

	private void AuthorithFilterMenu(Model model, HttpServletRequest request, String menuId) {
		HttpSession session = request.getSession();
		JgUser jgUser = (JgUser) session.getAttribute(Constants.user_session_jg_key);
		//取当前用户的权限列表
		if (jgUser != null) {
			List<AuthorityMenu> listAuthorithMenu = jgptUserService.queryAuthorityByUserId(jgUser.getId());

			for (int i = 0; i < listAuthorithMenu.size(); i++) {
				AuthorityMenu authorityMenu = listAuthorithMenu.get(i);
				if (authorityMenu.getMenuId().equals(menuId)) {
					authorityMenu.setCurrentStyleClass("current");
					break;
				}
			}

			model.addAttribute("authList", listAuthorithMenu);
		}
	}

	/**
	 * 获取监管平台-建设工程详情:分页
	 * @param model
	 * @return
	 */
	@RequestMapping("/jgpt/load_jgpt_page_data")
	public void getLoad_JgptPageList(Model model, int rows, int page, String searchText, HttpServletResponse response) {
		PageSearchModel qm = new PageSearchModel();
		qm.setPageNo(page);
		qm.setPageSize(rows);
		if (!StringUtils.isEmpty(searchText)) {
			try {
				searchText = URLDecoder.decode(searchText, "UTF-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		Page queryPage = jsgcProjectService.queryJsgcProjectInfo(qm, searchText);
		List<GgJsProjectInfo> noticeList = (List<GgJsProjectInfo>) queryPage.getResult();
		List<JgptProjectInfoVO> zbggList = new ArrayList<JgptProjectInfoVO>();
		for (GgJsProjectInfo project : noticeList) {
			JgptProjectInfoVO jgpt = new JgptProjectInfoVO();
			jgpt.setId(project.getId());
			jgpt.setProjectCode(project.getProjectCode());
			jgpt.setProjectName(project.getProjectName());
			jgpt.setProjectType(jsgcProjectService.getProjectTypeByCode(project.getProjectType()));
			jgpt.setZblb(project.getBidClasses());
			jgpt.setYsj(project.getBudgetPrice());
			jgpt.setOperation("查看");
			zbggList.add(jgpt);
		}
		queryPage.setResult(zbggList);
		String jsonStr = "";
		try {
			jsonStr = JsonUtils.toJsonStr(queryPage);
			response.getWriter().write(jsonStr);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 项目招标统计-监管平台
	 * @param model
	 * @return
	 */
	@RequestMapping("/jgpt/jgpt_wszbfx")
	public String getJgptXmzbtj(Model model) {
		model.addAttribute("voName", new Object());
		return "/jgpt/jgpt_wszbfx";
	}

	/**
	 * 产权中标汇总分析-监管平台
	 * @param model
	 * @return
	 */
	@RequestMapping("/jgpt/jgpt_cqzbfx")
	public String getJgptCqzbhz(Model model) {
		model.addAttribute("voName", new Object());
		return "/jgpt/jgpt_cqzbfx";
	}

	/**
	 * 采购成交趋势分析-监管平台
	 * @param model
	 * @return
	 */
	@RequestMapping("/jgpt/jgpt_zfcg")
	public String getJgptCgcjqs(Model model, HttpServletRequest request, Date begin, Date end, String menuId) {
		if (begin == null) {
			Calendar instance = Calendar.getInstance();
			instance.set(Calendar.MONTH, 0);
			instance.set(Calendar.DATE, 1);
			instance.set(Calendar.HOUR_OF_DAY, 0);
			instance.set(Calendar.MINUTE, 0);
			instance.set(Calendar.SECOND, 0);
			begin = instance.getTime();
		}
		if (end == null) {
			Calendar instance = Calendar.getInstance();
			instance.set(Calendar.MONTH, 11);
			instance.set(Calendar.DATE, 31);
			instance.set(Calendar.HOUR_OF_DAY, 23);
			instance.set(Calendar.MINUTE, 59);
			instance.set(Calendar.SECOND, 59);
			end = instance.getTime();
		}

		String beginDate = TimeUtil.getDate(begin);
		String endDate = TimeUtil.getDate(end);

		List<ZfcgStaticsVO> zfcgStaticsVOList = jgptZfcgService.getZfcgStaticsVO(begin, end);
		//获取数据
		ZfcgStaticsVO zfcgStaticsVO = new ZfcgStaticsVO();
		if (zfcgStaticsVOList.size() > 0)
			zfcgStaticsVO = zfcgStaticsVOList.get(0);
		//表格数据
		model.addAttribute("x_zhou", Tools.getDateBrStr(beginDate, endDate));

		/**************折线图*********************/
		//y轴
		Map<String, ZfcgStaticsVO> dataMap = zfcgStaticsVO.getDataMap();
		List<String> dateList = Tools.getDateList(beginDate, endDate);
		String y_zhou = "";

		for (int i = 0; i < dateList.size(); i++) {
			String key = dateList.get(i);
			ZfcgStaticsVO tempVO = dataMap.get(key);
			double sum;
			if (tempVO == null) {
				sum = 0;
			} else {
				sum = tempVO.getSum();
			}
			y_zhou = y_zhou + sum;
			if (i < dateList.size() - 1) {
				y_zhou = y_zhou + ",";
			}
		}

		model.addAttribute("y_zhou", y_zhou);

		/*******************饼图*****************/

		List<String> dateBrList = Tools.getDateBrList(beginDate, endDate);
		List<DataInfo> bztList = new ArrayList<DataInfo>();
		for (int i = 0; i < dateBrList.size(); i++) {
			DataInfo info = new DataInfo();
			String key = dateList.get(i);
			ZfcgStaticsVO tempVO = dataMap.get(key);
			Double value = new Double(0);
			if (tempVO != null)
				value = tempVO.getSum();

			info.setKey(dateBrList.get(i));
			info.setValue(value);
			bztList.add(info);

		}

		/*******************处理表格列表***************************/
		DateFormat dfm = new SimpleDateFormat("yyyy-MM");
		Calendar cal = Calendar.getInstance();
		cal.setTime(begin);
		List<ZfcgStaticsVO> resultList = new ArrayList<ZfcgStaticsVO>();
		Date calBeginMoth = new Date(begin.getTime());
		while (!calBeginMoth.after(end)) {
			if (dataMap.get(dfm.format(calBeginMoth)) != null) {
				resultList.add(dataMap.get(dfm.format(calBeginMoth)));
			} else {
				ZfcgStaticsVO tempVO = new ZfcgStaticsVO();
				tempVO.setCgrs("0");
				tempVO.setGysrs("0");
				tempVO.setPersent(0);
				tempVO.setYear_month(dfm.format(calBeginMoth));
				resultList.add(tempVO);
			}
			cal.add(Calendar.MONTH, 1);
			calBeginMoth = cal.getTime();
		}

		model.addAttribute("begin", beginDate);
		model.addAttribute("end", endDate);

		model.addAttribute("list", resultList);
		model.addAttribute("bzt_list", bztList);

		model.addAttribute("zfcgStaticsVO", zfcgStaticsVO);

		/*****************增加权限*********************/

		AuthorithFilterMenu(model, request, menuId);

		return "/jgpt/jgpt_zfcg";
	}

	/**
	 * 采购成交趋势分析-监管平台
	 * @param model
	 * @return
	 */
	@RequestMapping("/jgpt/jgpt_cqjy")
	public String getCqjyData(Model model, HttpServletRequest request, Date begin, Date end, String menuId) {
		if (begin == null) {
			Calendar instance = Calendar.getInstance();
			instance.set(Calendar.MONTH, 0);
			instance.set(Calendar.DATE, 1);
			instance.set(Calendar.HOUR_OF_DAY, 0);
			instance.set(Calendar.MINUTE, 0);
			instance.set(Calendar.SECOND, 0);
			begin = instance.getTime();
		}
		if (end == null) {
			//end = new Date();
			Calendar instance = Calendar.getInstance();
			instance.set(Calendar.MONTH, 11);
			instance.set(Calendar.DATE, 31);
			instance.set(Calendar.HOUR_OF_DAY, 23);
			instance.set(Calendar.MINUTE, 59);
			instance.set(Calendar.SECOND, 59);
			end = instance.getTime();
		}
		DateFormat dfm = new SimpleDateFormat("yyyy-MM");
		try {
			List<JgptCqjy> gkjjList = jgptCqjyService.getCqjyData(begin, end, "国有及国有控股企业");
			List<JgptCqjy> ztbList = jgptCqjyService.getCqjyData(begin, end, "非国有企业");
			List<JgptCqjy> pmList = jgptCqjyService.getCqjyData(begin, end, "国有参股企业");
			List<JgptCqjy> wzList = jgptCqjyService.getCqjyData(begin, end, "外资企业");
			List<JgptCqjy> qtList = jgptCqjyService.getCqjyData(begin, end, "其他");
			model.addAttribute("gkjjMap", this.getTotalData(gkjjList, dfm, Tools.formatDateToString(begin), Tools.formatDateToString(end)));
			model.addAttribute("ztbMap", this.getTotalData(ztbList, dfm, Tools.formatDateToString(begin), Tools.formatDateToString(end)));
			model.addAttribute("pmMap", this.getTotalData(pmList, dfm, Tools.formatDateToString(begin), Tools.formatDateToString(end)));
			model.addAttribute("wzMap", this.getTotalData(wzList, dfm, Tools.formatDateToString(begin), Tools.formatDateToString(end)));
			model.addAttribute("qtMap", this.getTotalData(qtList, dfm, Tools.formatDateToString(begin), Tools.formatDateToString(end)));
		} catch (Exception e) {
			e.printStackTrace();
		}
		model.addAttribute("begin", Tools.formatDateToString(begin));
		model.addAttribute("end", Tools.formatDateToString(end));

		/*****************增加权限*********************/

		AuthorithFilterMenu(model, request, menuId);

		return "/jgpt/jgpt_cqjy";
	}

	private Map<String, JgptCqjy> getTotalData(List<JgptCqjy> cqjyList, DateFormat dfm, String beginStr, String endStr) {
		Map<String, JgptCqjy> dateMap = new TreeMap<String, JgptCqjy>();
		for (JgptCqjy jgpt : cqjyList) {
			dateMap.put(jgpt.getDate(), jgpt);
		}
		//补一下没有数据的月份
		Date calBeginMoth;
		try {
			calBeginMoth = dfm.parse(beginStr);
			Date calEndMoth = dfm.parse(endStr);
			Calendar cal = Calendar.getInstance();
			cal.setTime(calBeginMoth);
			while (!calBeginMoth.after(calEndMoth)) {
				if (dateMap.get(dfm.format(calBeginMoth)) == null) {
					dateMap.put(dfm.format(calBeginMoth), new JgptCqjy(dfm.format(calBeginMoth), 0, 0));
				}
				cal.add(Calendar.MONTH, 1);
				calBeginMoth = cal.getTime();
			}
			return dateMap;
		} catch (ParseException e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 采购成交趋势分析-监管平台
	 * @param model
	 * @return
	 */
	@RequestMapping("/jgpt/get_project_data")
	public ModelAndView getProjectData(String id) {
		DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		ModelAndView mv = new ModelAndView("jsonView");
		List<GgJsSchedule> sList = jsgcProjectService.queryJsgcScheduleInfo(id);
		JgptProject prj = new JgptProject();
		if (sList != null) {
			for (GgJsSchedule s : sList) {
				if ("106".equals(s.getWorkAgendaKey().trim())) {//招标公告时间
					prj.setNoticePublishDate(s.getStartTime());
				} else if ("36".equals(s.getWorkAgendaKey().trim())) {//报名时间
					prj.setEnrollEndDate(s.getEtartTime());
				} else if ("48".equals(s.getWorkAgendaKey().trim())) {//开标时间
					prj.setOpenBidDate(s.getEtartTime());
				} else if ("50".equals(s.getWorkAgendaKey().trim())) {//中标公示时间
					prj.setResultStartDate(s.getStartTime());
					prj.setResultEndDate(s.getEtartTime());
				}
			}
			mv.addObject(prj);
			mv.addObject("nowDate", df.format(new Date()));
		}
		return mv;
	}

	/**
	 * 采购成交趋势分析-监管平台
	 * @param model
	 * @return
	 */
	@RequestMapping("/jgpt/jgpt_jsgc")
	public String getJsgcData(Model model, HttpServletRequest request, Date begin, Date end, String menuId) {
		if (begin == null) {
			Calendar instance = Calendar.getInstance();
			instance.set(Calendar.MONTH, 0);
			instance.set(Calendar.DATE, 1);
			instance.set(Calendar.HOUR_OF_DAY, 0);
			instance.set(Calendar.MINUTE, 0);
			instance.set(Calendar.SECOND, 0);
			begin = instance.getTime();
		}
		if (end == null) {
			//end = new Date();
			Calendar instance = Calendar.getInstance();
			instance.set(Calendar.MONTH, 11);
			instance.set(Calendar.DATE, 31);
			instance.set(Calendar.HOUR_OF_DAY, 23);
			instance.set(Calendar.MINUTE, 59);
			instance.set(Calendar.SECOND, 59);
			end = instance.getTime();
		}

		DateFormat dfm = new SimpleDateFormat("yyyy-MM");

		try {

			List<JgptJsgcDetail> jsgcList = jsgcProjectService.getJgptJsgcData(begin, end);
			Map<String, JgptJsgcDetail> dateMap = new TreeMap<String, JgptJsgcDetail>();
			for (JgptJsgcDetail jgpt : jsgcList) {
				dateMap.put(jgpt.getDate(), jgpt);
			}
			//补一下没有数据的月份
			Date calBeginMoth = dfm.parse(Tools.formatDateToString(begin));
			Date calEndMoth = dfm.parse(Tools.formatDateToString(end));
			Calendar cal = Calendar.getInstance();
			cal.setTime(calBeginMoth);
			while (!calBeginMoth.after(calEndMoth)) {
				if (dateMap.get(dfm.format(calBeginMoth)) == null) {
					JgptJsgcDetail detail = new JgptJsgcDetail();
					detail.setDate(dfm.format(calBeginMoth));
					detail.setNums(0);
					detail.setPrices(0);
					detail.setSggs(0);
					detail.setSgjezb(0);
					detail.setSgysj(0);
					detail.setJlgs(0);
					detail.setJljezb(0);
					detail.setJlysj(0);
					detail.setKcgs(0);
					detail.setKcjezb(0);
					detail.setKcysj(0);
					detail.setSjgs(0);
					detail.setSjjezb(0);
					detail.setSjysj(0);
					dateMap.put(dfm.format(calBeginMoth), detail);
				}
				cal.add(Calendar.MONTH, 1);
				calBeginMoth = cal.getTime();
			}
			model.addAttribute("dateMap", dateMap);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		model.addAttribute("begin", Tools.formatDateToString(begin));
		model.addAttribute("end", Tools.formatDateToString(end));

		/*****************增加权限*********************/

		AuthorithFilterMenu(model, request, menuId);

		return "/jgpt/jgpt_jsgc";
	}

}
